<template>
  <div class="app-container">
    <div class="Header">
      <edit-form ref="editFormContainer" v-show="showSearch" :inline="true" :editFormMap="userFilterMap" :editFormData="queryParams">
        <template slot="buttonGroup">
          <el-col :span="3">
            <el-form-item class="buttonGroup">
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </template>
      </edit-form>
      <handle-button-group
        :showSearch.sync="showSearch"
        :single="single"
        :multiple="multiple"
        :authModule="{ module: 'user', name: 'user' }"
        @handleAdd="handleAdd"
        @handleUpdate="handleUpdate"
        @handleDelete="handleDelete"
        @handleExport="handleExport"
        @getList="getList"
      />
    </div>
    <table-list
      ref="tableListContainer"
      :tableListMap="userTableMap"
      :request="{
        apiKey: 'userUserList',
        params: queryParams,
        method: 'get',
      }"
      @selection-change="handleSelectionChange"
      @changeTableListAction="
        (TableList) => {
          userList = TableList;
        }
      "
    >
      <template slot="hasSelect">
        <el-table-column type="selection" width="55" :align="'center'" />
      </template>
      <template slot="hasHandle">
        <el-table-column label="操作" :align="'center'">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['user:user:edit']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['user:user:remove']">删除</el-button>
          </template>
        </el-table-column>
      </template>
    </table-list>
    <!-- <el-table-column label="状态" align="center" prop="status">
      <template slot-scope="scope">
        <dict-tag :options="dict.type.gen_user_status" :value="scope.row.status" />
      </template>
    </el-table-column>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" /> -->

    <!-- 添加或修改会员对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      class="dialog-box"
      @close="cancel"
    >
      <BasicInfo
        ref="userBasicForm"
        :editFormData="userBasicForm"
        :editFormMap="editType === 'add' ? userBasicInfo : handleUserBasicInfo"
        :editFormRule="userBasicRule"
        @changeAction="changeAction"
        @getFormOptionListMap="getFormOptionListMap"
      >
        <template v-if="editType === 'add'" slot="added">
          <el-descriptions-item>
            <template slot="label">头像</template>
            <el-form-item prop="avatar">
              <el-upload
                ref="upload"
                class="avatar-uploader"
                :limit="1"
                accept=".jpg, .png"
                :headers="uploadOption.headers"
                :file-list="uploadOption.fileList"
                :action="uploadOption.url"
                :show-file-list="false"
                :on-success="handleFileSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="userBasicForm.avatar" :src="userBasicForm.avatar" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-descriptions-item>
        </template>
      </BasicInfo>
      <ApproveInfo v-if="editType === 'add'" ref="userApproveForm" :editFormData="userApproveForm" :editFormMap="userApproveInfo" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUser, delUser, addUser, updateUser, exportUser } from '@/api/user/user';
import { getToken } from '@/utils/auth';
import { getDataSource } from '@/static/js/dataSource';
import { handleTreeArr } from '@/static/js/utils';
import BasicInfo from './components/BasicInfo';
import ApproveInfo from './components/ApproveInfo';
import cloneDeep from 'lodash/cloneDeep';
import { handleAddrCascader } from './utils';
import { assignData } from '@/utils';
export default {
  name: 'User',
  dicts: ['gen_user_status'],
  components: {
    BasicInfo,
    ApproveInfo,
  },
  computed: {
    userFilterMap() {
      return getDataSource('editForm', 'userFilterMap');
    },
    userTableMap() {
      return getDataSource('tableColumn', 'userTableMap');
    },
    userBasicInfo() {
      return getDataSource('editForm', 'userBasicInfo');
    },
    handleUserBasicInfo() {
      const userBasicInfo = cloneDeep(getDataSource('editForm', 'userBasicInfo'));
      const handleUserBasicInfo = [];
      const disableProp = ['realName', 'gender'];
      userBasicInfo.map((item) => {
        const handleItem = item;
        if (disableProp.includes(item.prop)) {
          handleItem.disabled = true;
        }
        handleUserBasicInfo.push(handleItem);
      });
      return handleUserBasicInfo;
    },
    userBasicRule() {
      return getDataSource('editRule', 'userBasicRule');
    },
    userApproveInfo() {
      return getDataSource('otherMap', 'userApproveInfo');
    },
  },
  watch: {
    open() {
      this.$nextTick(() => {
        const userBasicForm = this.$refs.userBasicForm;
        const editForm = userBasicForm.$refs.editForm;
        editForm.clearValidate();
      });
    },
  },
  data() {
    return {
      editType: 'add',
      cityOptions: [],
      cityProps: {
        value: 'id', // 指定选项的 值 为选项对象的某个属性值
        label: 'name', // 指定选项 标签 为选项对象的某个属性值
        children: 'chirdList', //指定选项的 子选项 为选项对象的某个属性值
      },
      addr: '', //所在地区
      // 上传参数
      uploadOption: {
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/file/alibyunupLoadFile',
        // 上传的文件列表
        fileList: [],
      },
      optionListMap: {},
      //年薪
      allSalaryList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      userList: [],
      // 下拉数据对象
      tableOptionMap: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {},
      // 表单参数
      userBasicForm: {},
      userApproveForm: {
        //实名认证
        faUserAuthenticationRealName: {
          realName: '',
          idCard: '',
          frontImage: '',
          backImage: '',
          auditStatus: '',
        },
        //学历认证
        faUserAuthenticationEdu: {
          eduId: '',
          school: '',
          eduImages: '',
          auditStatus: '',
        },
        //收入认证
        faUserAuthenticationSalary: {
          salaryId: '',
          salaryRemark: '',
          salaryImages: '',
          auditStatus: '',
        },
        //车辆认证
        faUserAuthenticationCar: {
          carStatus: '',
          carRemark: '',
          carImages: '',
          auditStatus: '',
        },
        //房产认证
        faUserAuthenticationHouse: {
          houseStatus: '',
          houseRemark: '',
          houseImages: '',
          auditStatus: '',
        },
      },
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.$nextTick(() => {
        this.$refs.tableListContainer.init();
      });
    },

    // 取消按钮
    cancel() {
      this.editType = 'add';
      this.open = false;
    },
    // 表单重置
    reset() {
      this.uploadOption.fileList = [];
      this.userBasicForm = this.$options.data().userBasicForm;
      if (this.editType === 'update') {
        this.userApproveForm = this.$options.data().userApproveForm;
        const userApproveFormContainer = this.$refs.userApproveForm;
        userApproveFormContainer.albumImageList = this.$options.data().albumImageList;
        userApproveFormContainer.fileListMap = this.$options.data().fileListMap;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      const tableListContainer = this.$refs.tableListContainer;
      tableListContainer.pagination = tableListContainer.$options.data().pagination;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      const editFormContainer = this.$refs.editFormContainer;
      editFormContainer.resetForm('editFormData');
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.editType = 'add';
      this.reset();
      this.open = true;
      this.title = '添加会员';
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.editType = 'update';
      // 获取下拉列表数据
      const id = row ? row.id : this.ids.join(',');
      getUser(id).then(({ data }) => {
        const propList = this.userBasicInfo.map((item) => item.prop);
        const approvePropList = this.userApproveInfo.map((item) => item.approveFormName);
        const { locationProvince, locationCity, locationArea } = data;
        this.userBasicForm = cloneDeep({ ...assignData(data, propList), id: data.id, locationProvince, locationCity, locationArea });
        approvePropList.map((prop) => {
          this.userApproveForm[prop] = data[prop] || {};
        });
        this.$nextTick(() => {
          const userBasicForm = this.$refs.userBasicForm;
          const optionListMap = userBasicForm.optionListMap;
          // 组装地区组件数据
          if (optionListMap.addr && optionListMap.addr.length) {
            const { locationProvinceId, locationCityId, locationAreaId } = handleAddrCascader(optionListMap.addr, this.userBasicForm);
            this.$set(this.userBasicForm, 'addr', [locationProvinceId, locationCityId, locationAreaId]);
            this.$set(this.userBasicForm, 'locationProvinceId', locationProvinceId);
            this.$set(this.userBasicForm, 'locationCityId', locationCityId);
            this.$set(this.userBasicForm, 'locationAreaId', locationAreaId);
          }
        });
        this.open = true;
        this.title = '修改会员';
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row ? row.id : this.ids.join(',');
      this.$modal
        .confirm('是否确认删除Id编号为"' + ids + '"的数据项？')
        .then(function () {
          return delUser(ids);
        })
        .then(() => {
          this.getList();
          this.$message.success('删除成功');
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const tableListContainer = this.$refs.tableListContainer;
      const pagination = tableListContainer.pagination;
      const params = {
        ...pagination,
        ...this.queryParams,
      };
      exportUser(params, '会员数据导出');
    },
    changeAction({ prop }) {
      this.$nextTick(() => {
        const basicForm = this.$refs.userBasicForm;
        if (prop === 'addr' && this.userBasicForm[prop]) {
          // 获取当前选中节点的数组
          let addrNode = basicForm.$refs['addrCascader'][0].getCheckedNodes()[0];
          if (addrNode) {
            let pathLabels = addrNode.pathLabels;
            let path = addrNode.path;
            this.userBasicForm.locationProvince = pathLabels[0];
            this.userBasicForm.locationProvinceId = path[0];
            this.userBasicForm.locationCity = pathLabels[1];
            this.userBasicForm.locationCityId = path[1];
            this.userBasicForm.locationArea = pathLabels[2];
            this.userBasicForm.locationAreaId = path[2];
          }
        }
      });
    },
    getFormOptionListMap(optionListMap) {
      if (this.editType === 'update') return;
      setTimeout(() => {
        const approveFormContainer = this.$refs.userApproveForm;
        const optionArr = [];
        this.userApproveInfo.map((item) => {
          item.approveForm.map((formItem) => {
            optionArr.push(formItem);
          });
        });
        const optionKeyItem = optionArr.map((item) => {
          return { prop: item.prop, optionkey: item.optionkey };
        });
        optionKeyItem
          .filter((item) => item.optionkey)
          .map((item) => {
            optionListMap[item.prop] = approveFormContainer.getSimpleOption(item.optionkey);
          });
        approveFormContainer.optionListMap = cloneDeep(optionListMap);
      }, 1000);
    },
    /** 提交按钮 */
    submitForm() {
      const userBasicForm = this.$refs.userBasicForm;
      userBasicForm.$refs.editForm.validate((basicValid) => {
        if (basicValid) {
          if (this.editType === 'update') {
            const params = cloneDeep({ ...this.userBasicForm });
            updateUser(params).then(() => {
              this.$message.success('修改成功');
              this.open = false;
              this.getList();
            });
          } else {
            const userApproveFormContainer = this.$refs.userApproveForm;
            // 会员相册路径列表
            const albumImageList = userApproveFormContainer.albumImageList || [];
            // 过滤空认证对象
            const userApproveForm = {};
            Object.keys(this.userApproveForm).map((approveName) => {
              const approveObj = this.userApproveForm[approveName];
              let numFlag = 0;
              for (const key in approveObj) {
                if (approveObj[key]) {
                  numFlag++;
                }
              }
              if (numFlag) userApproveForm[approveName] = cloneDeep(approveObj);
            });
            // 所在地的省市区Id和名字
            const areaParam = {};
            const areaIdMap = ['locationProvinceId', 'locationCityId', 'locationAreaId'];
            const areaNameMap = ['locationProvince', 'locationCity', 'locationArea'];
            const areaArr = this.userBasicForm.addr;
            const userBasicForm = this.$refs.userBasicForm;
            const optionListMap = userBasicForm.optionListMap;
            const treeArr = handleTreeArr(optionListMap['addr'], 'chirdList');
            areaArr.map((areaId, areaIndex) => {
              const areaItem = treeArr.find((item) => item.id === areaId) || {};
              areaParam[areaIdMap[areaIndex]] = areaId;
              areaParam[areaNameMap[areaIndex]] = areaItem.name;
            });
            const params = cloneDeep({ ...this.userBasicForm, ...areaParam, ...userApproveForm, ...{ albumImageList } });
            delete params.addr;
            addUser(params).then(() => {
              this.$message.success('新增成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;
      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!');
      // }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      // return isJPG && isLt2M;
      return isLt2M;
    },
    // 头像上传成功处理
    handleFileSuccess({ data, msg }, file, fileList) {
      this.userBasicForm.avatar = data;
      this.uploadOption.fileList = [{ name: file.name, url: data }];
    },
  },
};
</script>
<style lang="scss" scoped>
.app-container {
  .Header {
    & ::v-deep .el-form-item.buttonGroup .el-form-item__content {
      width: 100%;
    }
  }
}
.avatar-uploader ::v-deep .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader ::v-deep .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 24px;
  color: #8c939d;
  width: 70px;
  height: 70px;
  line-height: 70px;
  text-align: center;
  border: 1px dashed #eee;
}
.avatar {
  width: 70px;
  height: 70px;
  display: block;
}
</style>
